﻿using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Reflection;
using CubicFWNet.Mvc.Models;
namespace CubicFWNet.Mvc.Filter
{
    public class AuthenAdminAttribute : FilterAttribute, IAuthenticationFilter
    {
        //这个方法是在Action执行之前调用
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            var returnUrl = "";
            if (request.Url != null)
            {
                returnUrl = request.Url.PathAndQuery;
            }
            var operatorModel = OperatorProvider.Provider.GetCurrent();
            if (operatorModel == null)
            {
                var Url = new UrlHelper(filterContext.RequestContext);
                var url = Url.Action("Index", "Login", new { returnUrl = returnUrl });
                filterContext.Result = new RedirectResult(url);
            }
            else
            {
                if (!operatorModel.IsSystem)
                {
                    //string Controllername = filterContext.RouteData.Values["controller"].ToString().ToLower();
                    //string Actionname = filterContext.ActionDescriptor.ActionName.ToLower();
                    //var function = this.GetType().GetMethods().FirstOrDefault(u => u.Name.ToLower() == Actionname);
                    //if (function == null)
                    //    throw new Exception("未能找到Action");
                    //var authorize = function.GetCustomAttribute(typeof(AuthenticateAttribute));
                    //ModuleApp app = new ModuleApp();
                    //var CurrentModule = app.LoadForUser().FirstOrDefault(u => u.Url != null && u.Url.ToLower().Contains(Controllername));
                    ////当前登录用户没有Action记录&&Action有authenticate标识
                    //if (authorize != null && CurrentModule == null)
                    //{
                    //    WebHelper.WriteCookie("cubic_login_error", "overdue");
                    //    //filterContext.HttpContext.Response.Write("<script>top.location.href = '/Login/Index';</script>");
                    //    filterContext.Result = new RedirectResult("/Login/Index");
                    //    return;
                    //}
                }
            }
        }

        //这个方法是在Action执行之后调用
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
        }
    }
}